﻿using System;
using ZX.Common;
using ZX.DBModule;
using ZX.Web.UI.Controls;
using ZX.BLL.Extend;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using ZX.Common.Extend;
using ZX.EHR.Library;

namespace ZX.WebApp.TR
{
    public partial class WeekPlan : EditPage
    {
        private DateTime dtnow
        {
            get
            {
                if (ViewState["dtnow"] != null)
                {
                    return (DateTime)ViewState["dtnow"];
                }
                else
                {
                    return DateTime.Now;
                }
            }
            set
            {
                ViewState["dtnow"] = value;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //dtnow = DateTime.Now.AddDays(7);
            AjaxPro.Utility.RegisterTypeForAjax(typeof(ZX.WebApp.TR.WeekPlan));
            if (!this.IsPostBack)
            { 
                string wpid = Request.QueryString["WPID"];
                int weekn=weekNum(dtnow.DayOfWeek);
                if (wpid == "")//新增时初始化数据
                {
                    ddlWeekNums.SelectedValue = weekn.ToString();
                    txtMonday.Text = GetFirstDay(dtnow.Year, weekn).ToString("yyyy-MM-dd");
                    txtFdate.Text = GetEndDay(dtnow.Year, weekn).ToString("yyyy-MM-dd");
                    DatUser du = (DatUser)Session["User"];
                    LabName.Text = du.UName;
                    Redirect(Convert.ToInt32(ddlWeekNums.SelectedValue),du.UserID);
                }
                else
                {
                    bangdata(new Guid(wpid));
                }
            }
        }

        protected void Redirect(int ws,Guid guid)
        {
            ZX.TR.Library.TrWeekPlan twp = new ZX.TR.Library.TrWeekPlan();
            BaseBussnies bwp = new BaseBussnies(twp);
            IList<ZX.TR.Library.TrWeekPlan> twpl = bwp.GetEntitys<ZX.TR.Library.TrWeekPlan>(" WeekNums=" + ws + " and AddUser='" + guid + "'");
            if (twpl != null)
            {
                bangdata(twpl[0].TrWeekPlanID);
            }
            else
            {
                hdfpid.Value = "";
                hdfWWValue.Value = "";
                HdfDiv.Value = "1";
                TaRequest.Value = "";
                TaWeekPoint.Value = "";
            }
        }

        protected void ddlWeekNums_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            int ws = Convert.ToInt32(ddlWeekNums.SelectedValue);
            int y = dtnow.Year;
            txtMonday.Text = GetFirstDay(y, ws).ToString("yyyy-MM-dd");
            txtFdate.Text = GetEndDay(y, ws).ToString("yyyy-MM-dd");
            DatUser du = (DatUser)Session["User"];
            Redirect(ws, du.UserID);
        }

        #region 周次转换
        protected void BandWeekNums(int y,int d)
        {
            decimal y4 = (y - 1) / 4;
            decimal y100 = (y - 1) / 100;
            decimal y400 = (y - 1) / 400;
            decimal w = (y - 1) + Math.Floor(y4) - Math.Floor(y100) + Math.Floor(y400) + d;
            int w1 = Convert.ToInt32(w);
            int weeks = w1 % 7;

            string StartDate = dtnow.AddDays(-weeks + 1).ToShortDateString();
            string EndDate = dtnow.AddDays(5 - weeks).ToShortDateString();


            int weeknow =weeks;//今天星期几
            int daydiff = (-1) * (weeknow + 1);//今日与上周末的天数差
            int days = dtnow.AddDays(daydiff).DayOfYear;//上周末是本年第几天
            int ws = days / 7;
            if (days % 7 != 0)
            {
                ws++;
            }
            int sum=ws + 2;
        }

        ////根据传入年份第几周返回该周星期天的日期
        protected DateTime GetFirstDay(int y, int ws)
        {
            int l = GetLeavingsDay(y);
            int days;
            int dayns = dtnow.DayOfYear;
            if (l > 3)
                days = ws * 7-l;
            else
                days = ws * 7+l;

            DateTime dtwd = dtnow.AddDays(days - dayns);//周中日期


            if (days < 7)
            {
                return Convert.ToDateTime(y.ToString() + "-1-1");
            }
            else
            {
                return dtnow.AddDays(days - dayns - 6);
            }
        }

        
        //根据传入第几周返回该周星期六的日期
        protected DateTime GetEndDay(int y, int ws)
        {
            int l = GetLeavingsDay(y);
            int days;
            int dayns = dtnow.DayOfYear;
            if (l > 3)
                days = ws * 7 - l;
            else
                days = ws * 7 + l;

            DateTime dtwd = dtnow.AddDays(days - dayns);//周中日期


            if (days < 7)
            {
                return Convert.ToDateTime(y.ToString() + "-1-1").AddDays(l);
            }
            else
            {
                return dtnow.AddDays(days - dayns);
            }
        }


        //返回星期几
        protected int GetWeekDays(DateTime dt)
        {
            int y = dt.Year;
            int d = dt.DayOfYear;
            decimal y4 = (y - 1) / 4;
            decimal y100 = (y - 1) / 100;
            decimal y400 = (y - 1) / 400;
            decimal w = (y - 1) + Math.Floor(y4) - Math.Floor(y100) + Math.Floor(y400) + d; 
            return Convert.ToInt32(w) % 7;
        }

        //返回上年度星期遗留天数
        protected int GetLeavingsDay(int y)
        {
            int wds = GetWeekDays(Convert.ToDateTime(y+"-1-1"));
            int lds=7 - wds;
            if (lds != 7)
                return lds;
            else
                return 0;
        }


        //本周是本年第几周
        private int weekNum(System.DayOfWeek dw)    
        {
            int weeknow =Convert.ToInt32(dw);//今天星期几
            int daydiff = (-1) * (weeknow + 1);//今日与上周末的天数差
            int days = dtnow.AddDays(daydiff).DayOfYear;//上周末是本年第几天
            int dayns = dtnow.DayOfYear;//今天为本年度第几天
            bool ky = false;
            if (dayns < days)
                ky=true;
            int weeks = days / 7;
            if (days % 7 != 0)
            {
                weeks++;
            }

            int l = GetLeavingsDay(dtnow.Year);
            if (l < 3 && ky&&dayns>l)
            {
                return 1;
            }
            else if (l > 2&&!ky)
            {
                return (weeks + 2);//当上年度遗留星期天数大于3天时，才作为本年度第一周
            }
            else
                return weeks+1;
        }
        #endregion
 
        //初始化数据
        protected void bangdata(Guid gid)
        {
            hdfpid.Value = gid.ToString();
            //周计划赋值
            DatUser du = (DatUser)Session["User"];
            ZX.TR.Library.V_TrWeekPlan twp = new ZX.TR.Library.V_TrWeekPlan();
            BaseBussnies bwp = new BaseBussnies(twp);
            IList<ZX.TR.Library.V_TrWeekPlan> twpl = bwp.GetEntitys<ZX.TR.Library.V_TrWeekPlan>("TrWeekPlanID='" + gid + "'");
            LabName.Text = GetUserName(twpl[0].AddUser);
            ddlWeekNums.SelectedValue = twpl[0].WeekNums.ToString();
            //ddlWeekNums.Enabled = false;
            txtMonday.Text = twpl[0].StartTime.ToString("yyyy-MM-dd");
            txtFdate.Text = twpl[0].EndTime.ToString("yyyy-MM-dd");
            TaMonthAim.Value = twpl[0].MonthAim;
            TaRequest.Value = twpl[0].Request;
            TaWeekPoint.Value = twpl[0].WorkPoint;

            ZX.TR.Library.V_TrWeekWork tww = new ZX.TR.Library.V_TrWeekWork();
            BaseBussnies bww = new BaseBussnies(tww);
            bww.Order = "TrWeekWorkID";
            bww.Desc = "Yes";
            IList<ZX.TR.Library.V_TrWeekWork> twwl = bww.GetEntitys<ZX.TR.Library.V_TrWeekWork>("TrWeekPlanID='" + gid + "' and WorkType='N'");
            //工作项赋值
            HdfDiv.Value = twwl.Count.ToString();
            StringBuilder sb = new StringBuilder();
            foreach (ZX.TR.Library.V_TrWeekWork ww in twwl)
            {
                sb.Append(ww.TrWeekWorkID + "|");
                sb.Append(ww.PlanWork + "|");
                sb.Append(ww.PreResult + "|");
                //sb.Append(ww.UName + "|");
                sb.Append(ww.W1+"|");
                sb.Append(ww.W2 + "|");
                sb.Append(ww.W3 + "|");
                sb.Append(ww.W4 + "|");
                sb.Append(ww.W5 + "|");
                sb.Append(ww.W6 + "|");
                sb.Append(ww.W7 + "|");
                sb.Append(ww.PlanSelf + "|");
                sb.Append("^");
            }
            hdfWWValue.Value = sb.ToString();
            Page.ClientScript.RegisterStartupScript(this.GetType(), "Review", "ReviewForm()", true);
        }


        protected string GetUserName(Guid uid)
        {
            ZX.EHR.Library.DatUser du = new ZX.EHR.Library.DatUser();
            BaseBussnies bdu = new BaseBussnies(du);
            IList<ZX.EHR.Library.DatUser> dul = bdu.GetEntitys<ZX.EHR.Library.DatUser>("Userid='" + uid + "'");
            return dul[0].UName;
        }
        #region AJAX方法区

        //检查人检测
        [AjaxPro.AjaxMethod]
        public string CheckUser(string users)
        {
            string[] us = users.Split(';');
            ZX.EHR.Library.DatUser du = new ZX.EHR.Library.DatUser();
            BaseBussnies bdu = new BaseBussnies(du);
            StringBuilder sbuid = new StringBuilder();

            foreach (string user in us)
            {
                if (user == "")
                    continue;
                //IList<ZX.EHR.Library.DatUser> dul = bdu.GetEntitys<ZX.EHR.Library.DatUser>("MessageType='公告' and IsPublic='是'");
                IList<ZX.EHR.Library.DatUser> dul = bdu.GetEntitys<ZX.EHR.Library.DatUser>("UName='" + user + "'");
                if (dul==null)//用户不存在
                {
                    sbuid.Append("检查人[" + user + "]不存在，请重新填写;");
                }
                else if (dul.Count > 1)//用户数大于1
                {
                    sbuid.Append("检查人[" + user + "]存在多个，请按【登录账号】填写;");
                }
                else
                {
                    sbuid.Append(dul[0].UserID+";");
                }
            }
            return sbuid.ToString();
        }
        //保存数据
        [AjaxPro.AjaxMethod]
        public int SavePlan(string str)
        {
            if (str == "")
                return 0;
            string[] strs = str.Split('&');
            ZX.TR.Library.TrWeekPlan twp = new ZX.TR.Library.TrWeekPlan();
            //插入主表信息
            if (strs[0] != "")
            {
                string[] mains = strs[0].Split('^');
                DatUser du = (DatUser)Session["User"];
                twp.AddTime = dtnow;
                twp.AddUser = du.UserID;
                twp.HrHumanID = du.UserID;
                twp.WeekNums=Convert.ToInt32(mains[1]);
                twp.StartTime = Convert.ToDateTime(mains[2]);
                twp.EndTime = Convert.ToDateTime(mains[3]);
                twp.MonthAim = mains[4];
                twp.WorkPoint = mains[5];
                twp.Request = mains[6];
                
                if (mains[0] == "")
                {
                    BaseBussnies bdu = new BaseBussnies(twp);
                    IList<ZX.TR.Library.TrWeekPlan> dul = bdu.GetEntitys<ZX.TR.Library.TrWeekPlan>("AddUser='" + du.UserID + "' AND WeekNums=" + twp.WeekNums);
                    if (dul == null)
                    {
                        twp.TrWeekPlanID = Guid.NewGuid();
                        BaseBussnies bli = new BaseBussnies(twp);
                        bli.Insert();
                    }
                    else
                    {
                        twp.TrWeekPlanID =dul[0].TrWeekPlanID;
                        BaseBussnies blu = new BaseBussnies(twp);
                        blu.Update();
                    }
                }
                else
                {
                    twp.TrWeekPlanID =new Guid(mains[0]);
                    BaseBussnies blu = new BaseBussnies(twp);
                    blu.Update();
                }
            }
            //插入从表信息
            if (strs[1] != ""&&strs[2]!="")
            {
                string wwv = strs[2];
                string[] wvs = wwv.Split('^');
                StringBuilder sbd = new StringBuilder();//获取当前ID集
                for (int i = 0; i < wvs.Length - 1; i++)
                {
                    string[] details = wvs[i].Split('|');
                    ZX.TR.Library.TrWeekWork tww = new ZX.TR.Library.TrWeekWork();
                    
                    tww.TrWeekPlanID = twp.TrWeekPlanID;
                    tww.PlanWork = details[1];
                    tww.PreResult = details[2];
                    tww.W1 = details[3];
                    tww.W2 = details[4];
                    tww.W3 = details[5];
                    tww.W4 = details[6];
                    tww.W5 = details[7];
                    tww.W6 = details[8];
                    tww.W7 = details[9];
                    tww.WorkType = "N";
                    tww.PlanSelf = details[10];
                    if (details[0] == "")
                    {
                        tww.TrWeekWorkID = Guid.NewGuid();
                        sbd.Append(tww.TrWeekWorkID + ";");
                        BaseBussnies bi = new BaseBussnies(tww);
                        bi.Insert();
                    }
                    else
                    {
                        sbd.Append(details[0]+";");
                        tww.TrWeekWorkID = new Guid(details[0]);
                        BaseBussnies bu = new BaseBussnies(tww);
                        bu.Update();
                    }
                }
 
                //删除部分从表信息
                ZX.TR.Library.TrWeekWork twd = new ZX.TR.Library.TrWeekWork();
                BaseBussnies bww = new BaseBussnies(twd);
                IList<ZX.TR.Library.TrWeekWork> twdl = bww.GetEntitys<ZX.TR.Library.TrWeekWork>("TrWeekPlanID='" + strs[0] + "' and WorkType='N'");
                string[] wwids = sbd.ToString().Split(';');
                if (twdl != null&&(twdl.Count>(wwids.Length-1)))
                {
                    foreach (ZX.TR.Library.TrWeekWork v in twdl)
                    {
                        if (!sbd.ToString().Contains(v.TrWeekWorkID.ToString()))
                        {
                            bww.delete(v);
                        }
                    }
                }
            }
            return 1;
        }

        

        #endregion
    }
}